package com.marcosnobrega.android.threadservice;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.marcosnobrega.android.activity.AndroidNetwork;

import android.os.Handler;

public final class CheckMessagesThread implements Runnable{
	
	private String myAndroidId;
	private int lastCount;
	private Handler handler;
	private Runnable runnable;
	static final CheckMessagesThread checkThread = new CheckMessagesThread();
	
	public static final CheckMessagesThread getInstance(int count,String id,Handler mHandler,Runnable runnable){
		checkThread.lastCount = count;
		checkThread.myAndroidId = id;
		checkThread.handler = mHandler;
		checkThread.runnable = runnable;
		return checkThread;
	}
	
	private CheckMessagesThread(){}

	@Override
	public void run() {
		while(true){
			try {
				Thread.sleep(5000);
				loadMessages();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	private void loadMessages(){
		HttpPost request = new HttpPost(AndroidNetwork.getServiceUrl()+"?action="+AndroidNetwork.getActionListMessages());
		
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("userAndroidId", myAndroidId));
		
		DefaultHttpClient client = new DefaultHttpClient();
		try {
			request.setEntity(new UrlEncodedFormEntity(params));
			HttpResponse response = client.execute(request);
			HttpEntity entity = response.getEntity();
			String responseText = EntityUtils.toString(entity);
			if(!responseText.equalsIgnoreCase("")){
				String[] jsonStrings = responseText.split(";;;");
				if(jsonStrings.length > this.lastCount){
					this.lastCount = jsonStrings.length;
					this.handler.post(this.runnable);
					
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
